﻿using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using RestSharp;
using Wechatbot.Model;

namespace Wechatbot.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class ValuesController : ControllerBase
    {
        private const string ApiUrl = "https://api.link-ai.tech/v1/chat/completions";
        private const string ApiKey = "Bearer Link_nblOwxKXPKH09EabR2NPXdzhCQyJsoiQI8vIJCtuf3";

        [HttpPost("ReceiveMessage")]
        public async Task<IActionResult> ReceiveMessage([FromForm] WechatMessageModel message)
        {
            Console.WriteLine($"消息类型: Type={message.Type}, 内容={message.Content}，是@我的消息={message.IsMentioned}，是否是来自自己的消息={message.IsMsgFromSelf}");
            Console.WriteLine($"消息的相关发送方数据={message.Source}");
            var source = JsonConvert.DeserializeObject<SourceFrom>(message.Source);
            if (message.IsMentioned == "0")
            {
                Console.WriteLine($"不是@我的信息提前返回");
                return BadRequest(new { success = true, message = "不是@我的信息提前返回" });
            }
            if(message.Content == "@bot " || message.Content == "@bot")
            {
                return Ok(new { success = true, data = new { type = "text", content = $"@{source?.from?.payload?.name} 你好，有什么可以帮助你的" } });
            }
            
            var chatRequest = new ChatCompletionRequest
            {
                AppCode = "FyubB80p",
                Messages = new List<Message>
                {
                    new Message
                    {
                        Role = "user",
                        Content = message.Content
                    }
                },

            };

            var linkAiResponse = await CallLinkAI(chatRequest);

            if(linkAiResponse == null || linkAiResponse.Choices == null || !linkAiResponse.Choices.Any())
            {
                return Ok(new { success = true, data = new { type = "text", content = "未能获取有效的AI响应" } });
            }

            var botContent = $"@{source?.from?.payload?.name} {linkAiResponse.Choices.First().Message.Content}";

            // 构造返回给微信服务器的响应
            var response = new
            {
                success = true,
                data = new
                {
                    type = "text",
                    content = botContent
                }
            };
            return Ok(response);
        }

        [HttpPost]
        public async Task<LinkAiResponse> CallLinkAI([FromBody] ChatCompletionRequest request)
        {
            var client = new RestClient("https://api.link-ai.tech/v1/chat/completions");

            // 配置请求
            var restRequest = new RestRequest()
                .AddHeader("Authorization", ApiKey)
                .AddHeader("Content-Type", "application/json")
                .AddJsonBody(request); // 自动序列化为 JSON

            restRequest.Method = Method.Post;

            // 发送请求
            var response = await client.ExecuteAsync(restRequest);

            // 检查响应是否成功
            if (!response.IsSuccessful || string.IsNullOrEmpty(response.Content))
            {
                Console.WriteLine($"调用LinkAI失败: 状态码={response.StatusCode}, 错误={response.ErrorMessage}");
                return null;
            }

            // 解析响应 JSON
            return JsonConvert.DeserializeObject<LinkAiResponse>(response.Content);
        }
    }
}
